package com.ruoyi.project.mahjong.controller.api;


import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.domain.Result;
import com.ruoyi.framework.web.domain.TreeEntity;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.mahjong.domain.*;
import com.ruoyi.project.mahjong.domain.enu.ShopManager;
import com.ruoyi.project.mahjong.domain.vo.OpenTableRateVo;
import com.ruoyi.project.mahjong.domain.vo.ShiftMoneyInfoVo;
import com.ruoyi.project.mahjong.domain.vo.TableDianYuanVo;
import com.ruoyi.project.mahjong.domain.vo.WorkRecordVo;
import com.ruoyi.project.mahjong.mapper.TShopsMapper;
import com.ruoyi.project.mahjong.service.*;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.domain.SysUserRole;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.system.service.impl.SysRoleServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 店铺相关操作
 */
@RestController
@RequestMapping("/mahjong/myshops")
@Api(tags = "店铺相关操作api")
public class ShopsApiController  extends BaseController {
    @Autowired
    private TShopsMapper tShopsMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysRoleServiceImpl roleService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ITRecordService tRecordService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ITWorkService tWorkService;
    @Autowired
    private ITTablenumberService tablenumberService;
    @Autowired
    private ITRoomService roomService;
    @Autowired
    private IShopLogService shopLogService;

    /**
     * 查看分店
     * 展示所有店铺   登陆完进入页面就调这个接口
     * 我需要 根据员工id查询员工对应的店铺，以及员工是否负责人
     * 如果是总店负责人账号，则返回该总店旗下所有店铺
     * 如果不是店铺负责人则返回个空
     *
     * @return
     */

    @GetMapping("/list")
    @ApiOperation(value = "查看分店", httpMethod = "GET")
    public Result<SysDept> list() {
//         归属店铺
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysDept sysDept1 = new SysDept();
        SysUser sysUser = sysUserService.selectUserAllInfoById(user.getUserId());
        Long userId = sysUser.getUserId();

        Long deptId = sysUser.getDeptId();
        List<SysRole> roles = sysUser.getRoles();
        List<SysRole> roleList = roleService.selectRoleByUserId(userId);
        if (ObjectUtil.isNull(roleList)) {
            return Result.success("未查询到该用户角色信息");
        }

//        总店店长
        for(SysRole role:roleList) {
            if (role.getRoleId().toString().equals(ShopManager.MAXZONGDIAN.getValue())) {
                List<SysDept> sysDepts = deptService.selectDeptList(sysDept1);
                return Result.success(sysDepts);
            }
        }
        for(SysRole role:roleList) {
//        分店店长
            if (role.getRoleId().toString().equals(ShopManager.FENDIAN.getValue())) {
                List<SysDept> sysDepts = deptService.selectDeptListByDeptId(deptId);
                return Result.success(sysDepts);
            }
        }
//        普通店员
        return Result.success("店员账号");
    }

    @GetMapping("/addShopId/{shopId}")
    @ApiOperation(value = "点击操作分店", httpMethod = "GET")
    public Result<SysDept> addShopId(@PathVariable("shopId") Long shopId) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
//        redisCache.setCacheObject(Constants.SHOP_SUF+user.getUserId(),user.getDeptId());
        redisCache.setCacheObject(Constants.SHOP_SUF + user.getUserId(), shopId);
//        redisCache.getCacheObject(Constants.SHOP_SUF+user.getUserId());
        return Result.success(shopId);
    }

    /**
     * 员工列表
     *
     * @return
     */
    @GetMapping("/staffList")
    @ApiOperation(value = "员工列表", httpMethod = "GET")
    public Result<SysUser> staffList() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        List<SysUser> sysUsers = userMapper.selectUserListByShopId(shopId);
        return Result.success(sysUsers);
    }

    /**
     * 交班管理上班操作
     *
     * @return
     */
    @GetMapping("/goWork/{initMoney}")
    @ApiOperation(value = "上班操作", httpMethod = "GET")
    public Result shiftWork(@ApiParam("初始金额") @PathVariable("initMoney") String initMoney) {

        try {
            Long.valueOf(initMoney);
        } catch (Exception e) {
            throw new BaseException("请输入数字");
        }


        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        //检查是否下班
        String key = shopId + user.getUserId().toString();
        List<TWork> checkXb=tWorkService.check(user.getUserId(),shopId);
        if(ObjectUtil.isNotEmpty(checkXb)){
            redisCache.setCacheObject(key,checkXb.get(0).getId());
            return Result.error("需要先下班");
        }

        TWork tWork = new TWork();
        tWork.setSbTime(new Date());
        tWork.setStaffId(user.getUserId());
        tWork.setInitMoney(Long.valueOf(initMoney));
        tWork.setBak1(shopId.toString());
         shopLogService.saveLogGoWrok(tWork,shopId);
        int id = tWorkService.insertTWork(tWork);
        redisCache.setCacheObject(key, tWork.getId());
//        Long  jbid  = redisCache.getCacheObject(key);
        return Result.success("上班成功");
    }

    @Transactional
    @GetMapping("/offWork/{deliverMoney}/{remainingMoney}")
    @ApiOperation(value = "下班操作", httpMethod = "GET")
    @RepeatSubmit
    public Result offWork(@ApiParam("上交金额") @PathVariable("deliverMoney") String deliverMoney,
                          @ApiParam("余留金额") @PathVariable("remainingMoney") String remainingMoney) {
        Long deliverMoneys;
        Long remainingMoneys;
        try {
            deliverMoneys = Long.valueOf(deliverMoney);
            remainingMoneys = Long.valueOf(remainingMoney);
        } catch (Exception e) {
            throw new BaseException("请输入数字");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        Long jbid = redisCache.getCacheObject(shopId + user.getUserId().toString());
        ShiftMoneyInfoVo vo = tRecordService.selectShiftMoneyInfo(null, null, shopId, user.getUserId());
        TWork tWork = new TWork();
        tWork.setXbTime(new Date());
        tWork.setId(jbid);
        tWork.setDeliverMoney(deliverMoneys);
        tWork.setRemainingMoney(remainingMoneys);
        tWork.setCashMoney(vo.getCashMoney());
        tWork.setScanMoney(vo.getScanMoney());
        tWork.setOutMoney(vo.getOutMoney());
        tWork.setAllMoney(vo.getAllMoney());
        tWork.setOtherMoney(vo.getOtherMoney());
        tWork.setSendMoney(vo.getSendMoney());
        tWork.setRefendMoney(vo.getRefendMoney());
        tWork.setUpdateBy(user.getUserId().toString());
        tWork.setUpdateTime(new Date());
        shopLogService.saveLogDowmWrok(tWork,shopId);
        Integer i = tWorkService.updateTWork(tWork);
       /* if (i == 0) {
            throw new BaseException("下班信息数据修改失败,请重试");
        }*/
        redisCache.deleteObject(shopId + user.getUserId().toString());
        return Result.success("下班成功");
    }

    /**
     * 交班收入金额
     *
     * @return
     */
    @GetMapping("/moneyInfo")
    @ApiOperation(value = "交班金额详情", httpMethod = "GET")
    public Result<ShiftMoneyInfoVo> shiftWorkInfo(@ApiParam("开始时间") @RequestParam(value = "startTime", required = false) String startTime,
                                                  @ApiParam("结束时间") @RequestParam(value = "endTime", required = false) String endTime) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
       /* if(user.isAdmin()){
            shopId=null;
        }*/
        ShiftMoneyInfoVo vo = tRecordService.selectShiftMoneyInfo(startTime, endTime, shopId, user.getUserId());
        vo.setUserName(user.getUserName());
//        vo.setUpWorkTime();
        return Result.success(vo);
    }

    /**
     * 查询桌号列表
     *
     * @return
     */
    @GetMapping("/getTableList")
    @ApiOperation(value = "查询桌号列表", httpMethod = "GET")
    public Result<TRoom> getTableList() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        List<TRoom> rooms = roomService.selectRoomListByShopId(shopId);
        if (ObjectUtil.isEmpty(rooms)) {
            throw new BaseException("暂无房间信息");
        }
        List<TTablenumber> tTablenumbers = tablenumberService.selectTableListByShopId(shopId);
        if (ObjectUtil.isEmpty(tTablenumbers)) {
            throw new BaseException("暂无桌子信息");
        }
        for (TRoom room : rooms) {
            List<TTablenumber> t = new ArrayList<>();

            Long roomId = room.getId();
            for (TTablenumber tablenumber : tTablenumbers) {
                if (tablenumber.getRoomType().equals(roomId.toString())) {
                    t.add(tablenumber);
                }
            }
            room.settTablenumbers(t);
        }

        return Result.success(rooms);
    }

    /**
     * 交班记录
     *
     * @return
     */
    @GetMapping("/workRecord")
    @ApiOperation(value = "交班记录", httpMethod = "GET")
    public TableDataInfo workRecord(@ApiParam("开始时间") @RequestParam(value = "startTime", required = false) String startTime,
                                    @ApiParam("结束时间") @RequestParam(value = "endTime", required = false) String endTime,  @ApiParam("结束时间") @RequestParam(value = "staffName", required = false) String staffName) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        startPage();
        List<WorkRecordVo> workRecordVos = tWorkService.selectWorkRecordList(startTime, endTime, shopId,staffName);
        return getDataTable(workRecordVos);
    }

    /**
     * 经营走势 上座率
     *
     * @return
     */
    @GetMapping("/openTableRate")
    @ApiOperation(value = "经营走势上座率", httpMethod = "GET")
    public Result<WorkRecordVo> openTableRate() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());

        OpenTableRateVo workRecordVos = tRecordService.selectOenTableRate(shopId);
        return Result.success(workRecordVos);
    }
//    /**
//     * 收支明细
//     * @return
//     */
//    @GetMapping("/detailInfo")
//    @ApiOperation(value = "收支明细",httpMethod = "GET")
//    public Result<WorkRecordVo> detailInfo (@ApiParam("开始时间") @RequestParam(value = "startTime" ,required = false) String startTime,
//                                            @ApiParam("结束时间") @RequestParam(value = "endTime",required = false) String endTime,
//                                            @ApiParam("页码") @RequestParam(value ="page",required = false ,defaultValue = "0") int page,
//                                            @ApiParam("条数") @RequestParam(value ="pageSize",required = false,defaultValue = "10") int pageSize){
//        SysUser user = SecurityUtils.getLoginUser().getUser();
//        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
//        PageHelper.startPage(page,pageSize);
//        List <WorkRecordVo> workRecordVos= tWorkService.selectWorkRecordList(startTime,endTime,shopId);
//        return Result.success(workRecordVos);
//    }

    /**
     * 查看电源控制桌子列表
     *
     * @return
     */
    @GetMapping("/controlList")
    @ApiOperation(value = "查看电源控制桌子列表", httpMethod = "GET")
    public Result<TableDianYuanVo> control(@ApiParam("场地类型") @RequestParam(value = "roomId", required = false) Long roomId) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        List<TableDianYuanVo> vo = tablenumberService.selectTableListByShopIdAndRoomId(shopId, roomId);
        return Result.success(vo);
    }

    /**
     * 控制桌子店员
     *
     * @return
     */
    @GetMapping("/controDianYuan")
    @ApiOperation(value = "控制桌子店员", httpMethod = "GET")
    public Result<TableDianYuanVo> control(@ApiParam("桌子id") @RequestParam(value = "tableId", required = false) Long tableId,
                                           @ApiParam(" 1此桌子id通电 2 此桌子id断电") @RequestParam(value = "oneStatus", required = false) Long oneStatus,
                                           @ApiParam("是否所有桌台开关电源 1 所有通电 2 所有断电 4此桌子id通电 5 此桌子id断电") @RequestParam(value = "status", required = false) Long status) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        Integer i = tablenumberService.updateTableDianYuanStatus(tableId, status, shopId, oneStatus);
        return Result.success("控制电源成功");
    }
}
